package com.example.config;

import com.example.constant.ShiroConstants;
import com.example.exception.CaptchaException;
import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author code威
 * @version 1.0
 * @description: 自定义的userRealm  继承AuthorizingRealm
 * @date 2021/12/5 20:56
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    private static final transient Logger log = LoggerFactory.getLogger(UserRealm.class);

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("执行了-->授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        info.addStringPermission(user.getRole());
        //设置session
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("执行了-->认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //1.验证码验证
        ServletRequestAttributes attributes = (ServletRequestAttributes)  RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //验证码返回内容
        String msg = (String) request.getAttribute(ShiroConstants.CURRENT_CAPTCHA);
        if (ShiroConstants.CAPTCHA_ERROR_MSG.equals(msg)){
            throw new CaptchaException();
        }


        //2.用户名与密码认证
        User user = userService.queryUserByname(userToken.getUsername());
        log.info("数据库执行结果为："+user);
        //用户名认证,不存在返回false
        if (user == null){
            return null;//返回null,上层会抛出异常
        }
        //密码认证，shiro帮忙处理
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
